﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Linq;

using Kooboo.Connect;
using Kooboo.Globalization;
using Kooboo.Commerce;
using Kooboo.Web.Mvc;
using Kooboo.IoC;

using Kooboo.Commerce.Contexts.Customers;
using Kooboo.Commerce.Services;
using Kooboo.Commerce.AddIn;

using Kooboo.Web.Mvc.Paging;
using Kooboo.Commerce.Contexts.ShopSettings;
using Kooboo.Commerce.Contexts.SupportTickets;
using System.Web;

namespace Kooboo.Web.Controllers
{

    [HandleError]
    [Authorize(Roles = "Customer")]
    public class AccountController : ControllerBase
    {
        #region Profile
        [HttpGet]
        public ActionResult Index()
        {
            this.BindViewData();
            this.BindProfileLinks();



            Kooboo.Connect.User user = ContextContainer.Current.Resolve<Kooboo.Connect.User>();
            return View(user);
        }


        [HttpPost]
        public ActionResult Index(string firstName, string lastName)
        {

            Kooboo.Connect.User user = ContextContainer.Current.Resolve<Kooboo.Connect.User>();
            user.Profile.FirstName = firstName;
            user.Profile.LastName = lastName;
            Kooboo.Connect.UserServices.Save(user);

            this.BindViewData();
            this.BindProfileLinks();

            return View(user);
        }
        #endregion

        #region Password
        [HttpGet]
        public ActionResult Password()
        {
            this.BindViewData();
            this.BindProfileLinks();
            return View();
        }


        [HttpPost]
        public ActionResult Password(string oldPassword, string newPassword, string reNewPassword)
        {
            this.BindViewData();
            this.BindProfileLinks();

            UserServices.ChangePassword(this.HttpContext.User.Identity.Name, oldPassword, newPassword);
            return View();
        }
        #endregion

        #region Private

        void BindProfileLinks()
        {
            this.ViewBag.ProfileLinks = new
            {
                Profile = this.Url.Action<AccountController>(m => m.Index()),
                Password = this.Url.Action<AccountController>(m => m.Password()),
                Address = this.Url.Action<AccountController>(m => m.Address()),
                Order = this.Url.Action<AccountController>(m => m.Orderlist(null)),
                SupportTicket = this.Url.Action<AccountController>(m => m.SupportTicket(1))
            };
        }

        #endregion

        #region Address

        public ActionResult Address()
        {
            this.BindViewData();
            this.BindProfileLinks();
            this.BindCountry();
            ViewBag.Addresses = ContextContainer.Current.Resolve<Kooboo.Connect.User>().GetCustomer().Addresses;
            ViewBag.FormAction = Url.Action("Address");

            return View();
        }

        [HttpPost]
        public ActionResult Address(IAddress address)
        {
            //create address
            if (this.ModelState.IsValid)
            {
                ContextContainer.Current.Resolve<Kooboo.Connect.User>().GetCustomer().Post(address);
                return RedirectToAction("Address");
            }

            this.BindViewData();
            this.BindProfileLinks();
            this.BindCountry();
            ViewBag.Addresses = ContextContainer.Current.Resolve<Kooboo.Connect.User>().GetCustomer().Addresses;
            ViewBag.FormAction = Url.Action("Address");
            return View();
        }

        public ActionResult AddressEdit(int? id)
        {
            if ((id ?? 0) > 0)
            {
                IAddress address = ContextContainer.Current.Resolve<Kooboo.Connect.User>().GetCustomer().Addresses
                    .Where(a => a.Id == id).FirstOrDefault();
                if (address != null)
                {
                    ViewBag.Address = address;

                    this.BindViewData();
                    this.BindProfileLinks();
                    BindCountry(address.Country.CountryCode);
                    ViewBag.FormAction = Url.Action("AddressEdit", new { id = id.Value });
                    return View();
                }
            }
            return RedirectToAction("Address");
        }

        [HttpPost]
        public ActionResult AddressEdit(IAddress address)
        {
            if (this.ModelState.IsValid)
            {
                ContextContainer.Current.Resolve<Kooboo.Connect.User>().GetCustomer().Put(address);
                return RedirectToAction("Address");
            }

            this.BindViewData();
            this.BindProfileLinks();
            ViewBag.Address = address;
            BindCountry(address.Country.CountryCode);
            ViewBag.FormAction = Url.Action("AddressEdit", new { id = address.Id });
            return View();
        }

        #region Private method

        private void BindCountry(String selectedCode = null)
        {
            var service = new ItemService();
            this.ViewBag.CountryItems = service.GetCountriesWithCountyCode(selectedCode);
        }

        #endregion

        public ActionResult Delete(IAddress address)
        {
            ContextContainer.Current.Resolve<Kooboo.Connect.User>().GetCustomer().Delete(address);
            return RedirectToAction("Address");
        }

        #endregion

        #region Support Ticket

        public ActionResult SupportTicket(int? page)
        {
            this.BindViewData();
            this.BindProfileLinks();

            var user = ContextContainer.Current.Resolve<Kooboo.Connect.User>();

            this.ViewBag.CustomerId = user.GetCustomer().Id;
            this.ViewData["CustomerEmail"] = user.Email;

            var list = user.GetCustomer().SupportTickets;

            var pagedList = list.ToPagedList(page ?? 1, Kooboo.Commerce.Configuration.PageSize);

            return View(pagedList);
        }

        [HttpPost]
        public ActionResult SupportTicket(ISupportTicket supportTicket)
        {
            String message = String.Empty;

            if (String.IsNullOrEmpty(supportTicket.Subject))
            {
                return Json(new { Message = "Please enter subject".Localize() });    
            }

            if (String.IsNullOrEmpty(supportTicket.Email))
            {
                return Json(new { Message = "Please enter email address".Localize() });
            }

            if (String.IsNullOrEmpty(supportTicket.Body))
            {
                return Json(new { Message = "Please enter content".Localize() });
            }

            if (supportTicket.Body.Length > 1000)
            {
                return Json(new { Message = "Content exceed length limit".Localize() });
            }

            if (ModelState.IsValid)
            {
                supportTicket.CreateDate = DateTime.Now;
                ContextContainer.Current.Resolve<Kooboo.Connect.User>().GetCustomer().Post(supportTicket);
                return Json(true);
            }
            else
            {
                return Json(new { Message = ModelState.GetErrorMessages() });
            }
        }

        public ActionResult SupportTicketDetail(int id)
        {
            var user = ContextContainer.Current.Resolve<Kooboo.Connect.User>();

            var supportTicket = user.GetCustomer().SupportTickets
                .Where(s => s.Id == id).FirstOrDefault();
            if (supportTicket == null)
            {
                return RedirectToAction("SupportTicket");
            }

            this.BindViewData();
            this.BindProfileLinks();
            this.ViewBag.CustomerEmail = user.Email;

            return View(supportTicket);
        }

        [HttpPost]
        public ActionResult SupportTicketDetail(Int32 id, ISupportReply supportReply)
        {
            String message = String.Empty;

            if (String.IsNullOrEmpty(supportReply.Subject))
            {
                return Json(new { Message = "Please enter subject".Localize() });
            }

            if (String.IsNullOrEmpty(supportReply.Email))
            {
                return Json(new { Message = "Please enter email address".Localize() });
            }

            if (String.IsNullOrEmpty(supportReply.Body))
            {
                return Json(new { Message = "Please enter content".Localize() });
            }

            if (supportReply.Body.Length > 1000)
            {
                return Json(new { Message = "Content exceed length limit".Localize() });
            }

            if (ModelState.IsValid)
            {
                var user = ContextContainer.Current.Resolve<Kooboo.Connect.User>();

                var supportTicket = user.GetCustomer().SupportTickets
                    .Where(s => s.Id == id).FirstOrDefault();
                if (supportTicket != null)
                {
                    supportReply.IsAdminReply = false;
                    supportReply.UserName = user.GetCustomer().UserName;
                    supportReply.CreateDate = DateTime.Now;

                    supportTicket.SupportReplies.Add(supportReply);
                    user.GetCustomer().Put(supportTicket);
                }

                return Json(true);
            }
            else
            {
                return Json(new { Message = ModelState.GetErrorMessages() });
            }
        }


        #endregion

        public ActionResult Order(int orderid)
        {
            this.BindViewData();
            this.BindProfileLinks();
            ViewBag.Order = ContextContainer.Current.Resolve<Kooboo.Connect.User>().Order(orderid);
            return View();
        }

        public ActionResult Orderlist(int? page)
        {
            this.BindViewData();
            this.BindProfileLinks();

            var orderList = ContextContainer.Current.Resolve<Kooboo.Connect.User>().Orders().OrderByDescending(i => i.OrderDate)
                .ToPagedList(page ?? 1, Kooboo.Commerce.Configuration.PageSize);
            return View(orderList);
        }

        public ActionResult Thankyou()
        {
            this.BindViewData();
            this.BindProfileLinks();

            return View();
        }

        public ActionResult Error()
        {
            this.BindViewData();
            this.BindProfileLinks();

            this.ViewBag.Message = HttpUtility.UrlDecode(Request.QueryString["Message"]);
            return View();
        }

        [HttpPost]
        public ActionResult Pay(int orderId)
        {
            var order = ContextContainer.Current.Resolve<Kooboo.Connect.User>().Order(orderId);
            if (order != null)
            {
                var shopSettings = this.Actor.GetShopSettings();

                var thankYouPageUrl = Url.RouteUrl("web_account_order_thankyou", null, "http", this.Request.Url.Host);

                var method = ObjectContainer.CreateInstances<IPaymentMethod>()
                   .Where(i => i.Name == order.PaymentName)
                   .FirstOrDefault();

                method.ThankYouPageUrl = thankYouPageUrl;

                try
                {
                    method.TryToPay(order, shopSettings.CurrencyISOCode);
                }
                catch (Exception e)
                {
                    return RedirectToAction("Error", new { Message = e.Message });
                }
            }

            return View();
        }
    }
}
